package NIO;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class ChannelDemo {
    public static void main(String[] args) throws FileNotFoundException {

        RandomAccessFile rw = new RandomAccessFile("hello.txt", "rw");
        FileChannel channel = rw.getChannel();//获取channel对象

        ByteBuffer byteBuffer=ByteBuffer.allocate(10);
        do {
            try {
                //像buffer写入
                int len=channel.read(byteBuffer);
                if (len==-1){//-1代表没有数据可写了
                    System.out.println();
                    System.out.println("Done");
                    break;
                }

                //切换到读模式
                byteBuffer.flip();
                while(byteBuffer.hasRemaining()){
                    System.out.print((char) byteBuffer.get());
                }

                //切换回写模式
                byteBuffer.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }while (true);


    }
}
